package com.yuandengta.yomall.auth.controller;

import com.fasterxml.jackson.core.type.TypeReference;
import com.yuandengta.common.utils.CookieUtils;
import com.yuandengta.common.utils.IpUtils;
import com.yuandengta.common.utils.JwtUtils;
import com.yuandengta.common.utils.R;
import com.yuandengta.common.vo.MemberVO;
import com.yuandengta.yomall.auth.config.JwtProperties;
import com.yuandengta.yomall.auth.feign.MemberFeignService;
import com.yuandengta.yomall.auth.vo.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 认证授权 {@link AuthController}
 *
 * @author Kevin
 * @email: 178676392@qq.com
 */
@Controller
public class AuthController {

    @Autowired
    private MemberFeignService memberFeignService;

    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 登录页面-单点登录
     * @param returnUrl
     * @return
     */
    @GetMapping("/login2.html")
    public String login2Page(@RequestParam("returnUrl") String returnUrl, Model model) {
        // 把登录前的页面地址，记录到登录页面，以备将来登录成功，回到登录前的页面
        model.addAttribute("returnUrl", returnUrl);
        return "login2";
    }

    /**
     * 单点登录
     * @param account
     * @param password
     * @param returnUrl
     * @param request
     * @param response
     * @param redirectAttributes
     * @return
     */
    @PostMapping("/ssoLogin")
    public String ssoLogin(@RequestParam("account") String account,
                           @RequestParam("password") String password,
                           @RequestParam("returnUrl") String returnUrl,
                           HttpServletRequest request,
                           HttpServletResponse response,
                           RedirectAttributes redirectAttributes) {
        UserLoginVO vo = new UserLoginVO();
        vo.setAccount(account);
        vo.setPassword(password);
        // 调用远程接口
        R r = memberFeignService.login(vo);
        if (r.getCode() != 0) {
            Map<String, String> errors = new HashMap<>();
            String msg = r.getData("msg", new TypeReference<String>() {});
            errors.put("msg", msg);
            redirectAttributes.addFlashAttribute("errors", errors);
            // 登录失败，重定向到登录页面
            return "redirect:http://auth.yomall.com/login2.html";
        }

        // 3. 把用户id及用户名放入载荷
        MemberVO memberVO = r.getData("data", new TypeReference<MemberVO>() {});
        Map<String, Object> map = new HashMap<>();
        map.put("userId", memberVO.getId());
        map.put("username", memberVO.getNickname());

        // 4. 为了防止jwt被别人盗取，载荷中加入用户ip地址
        String ipAddress = IpUtils.getIpAddress(request);
        map.put("ip", ipAddress);

        // 5. 制作jwt类型的token信息
        try {
            String token = JwtUtils.generateToken(map, jwtProperties.getPrivateKey(), jwtProperties.getExpire());

            // 6. 把jwt放入cookie中
            CookieUtils.setCookie(request, response, jwtProperties.getCookieName(), token, jwtProperties.getExpire() * 60);
            // 7.用户昵称放入cookie中，方便页面展示昵称
            CookieUtils.setCookie(request, response, jwtProperties.getUnick(), memberVO.getNickname(), jwtProperties.getExpire() * 60);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "redirect:" + returnUrl;
    }
}
